// store.js

import { loginApi } from '@/api/login'
import $utils from 'xe-utils/date'
import { isNotNull } from '@/utils/common'


const userData = window.storage.get('userData') || {}
const day = $utils.toDateString(new Date(), 'yyyy-MM-dd')
const dailySignInRecord = window.storage.get('dailySignInRecord')

const store = {
  // 命名空间
  namespaced: true,
  state: {
    // profile
    userProfile: userData.profile,
    // cookie
    userCookie: '',
    // 是否进行了每日签到
    isDailySignIn: isNotNull(dailySignInRecord) ? dailySignInRecord.includes(day) : false
  },
  mutations: {
    /** 用户登录 */
    login(state, userData) {
      // 修改 state
      state.userProfile = userData.profile
      state.userCookie = userData.profile
    },
    /** 用户退出 */
    logout(state) {
      // 修改 state
      state.userProfile = null
      state.userCookie = ''
    },
    /** 每日签到 */
    dailySignIn(state) {
      state.isDailySignIn = true
    }
  },
  actions: {
    /** 用户登录 */
    login({ commit }, userData) {
      commit('login', userData)
      window.storage.set('userData', userData)
    },
    /** 用户退出 */
    logout({ commit }) {
      loginApi().logout().then(res => {
        window.storage.remove('userData')
        window.storage.remove('userDetails')
        window.storage.remove('token')
        console.log('remove')
        commit('logout')
      })
    },
    /** 每日签到 */
    dailySignIn({ commit }) {
      // set
      let dailySignInRecord = window.storage.get('dailySignInRecord')
      // 如果不存在则创建
      if (!isNotNull(dailySignInRecord)) {
        window.storage.set('dailySignInRecord', [])
        dailySignInRecord = window.storage.get('dailySignInRecord')
      }
      /** 获得今天的日期 2022/9/22 yyyy/m/dd */
      const day = $utils.toDateString(new Date(), 'yyyy-MM-dd')
      console.log('day: ', day)
      if (!dailySignInRecord.includes(day)) {
        // 添加今天签到的日期
        dailySignInRecord.push(day)
        // 持久化每日签到，新增到签到记录中
        window.storage.set('dailySignInRecord', dailySignInRecord)
        commit('dailySignIn')
      }
    }
  }
}

export default store
